<template>
  <div class="components-container">
    <aside style="font-size: small;">
      统一管理菜单的<strong>开放</strong>和<strong>关闭</strong>，只有<strong> 勾选 </strong> 的菜单才会开放给组织。
    </aside>
    <el-input v-model="filterText" placeholder="请输入关键字..." style="margin-bottom:10px;" />
    <el-tree ref="tree" show-checkbox :data="data" :filter-node-method="filterNode" :props="props" :node-key="nodeKey">
    </el-tree>
    <div style="margin: 20px;">
      <el-button type="primary" @click="submitMenus" :loading="loading">提交</el-button>
      <el-button type="infor" @click="reset">重置</el-button>
    </div>
  </div>
</template>

<script>
  import {
    mapGetters
  } from 'vuex'
  import {
    menuRoutes
  } from '@/router'
  import {
    deepClone
  } from '@/utils/index.js'
  import {
    SYS_MENU_API
  } from '@/api/systemApi.js'

  export default {
    data() {
      return {
        loading: false,
        filterText: '',
        data: [],
        nodeKey: 'path',
        props: {
          children: 'children',
          label: (data) => {
            if (data.meta) return data.meta.title;
            return data.children[0].meta.title;
          }
        }
      }
    },
    computed: {
      ...mapGetters([
        'groupId'
      ])
    },
    mounted() {
      this.data = deepClone(menuRoutes);
      this.loadInit();
    },
    methods: {
      async loadInit() {
        //获取开放的菜单列表
        let res = await SYS_MENU_API.listAdministratorOpenMenus();
        let data = res.data;
        if (data.length === 1 && data[0] === '*') {
          this.$refs.tree.setCheckedNodes(this.data);
        } else {
          this.$refs.tree.setCheckedKeys(data);
        }
      },
      async submitMenus() {
        this.loading = true;
        let keys = this.$refs.tree.getCheckedKeys();
        let params = {
          openPaths: keys.join(",")
        };
        let res = await SYS_MENU_API.updateAdministratorOpenMenus(params);
        this.$message({
          message: res.message,
          type: 'success'
        })
        this.loading = false;
      },
      reset() {
        this.$refs.tree.setCheckedKeys([]);
      },
      filterNode(value, data) {
        if (!value) return true
        if (data.meta) return data.meta.title.toUpperCase().indexOf(value.toUpperCase()) !== -1
        return data.children[0].meta.title.toUpperCase().indexOf(value.toUpperCase()) !== -1
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    }
  }
</script>
